package com.red.wood.module.questionnaire.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.red.wood.common.domain.Page;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.IMap;
import com.red.wood.module.questionnaire.service.QuestionnaireService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/questionnaireSt")
public class QuestionnaireStController {

	private static final Log log = LogFactory.getLog(QuestionnaireStController.class);
	
	@Autowired
	private QuestionnaireService service;
	
	/**
	 * 调查问卷列表统计
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("questionnaireSt");
		/*String referer = request.getHeader("Referer");
		if(StringUtils.isBlank(referer)) {
			mv = new ModelAndView("error");
		}*/
		return mv;
	}
	
	/**
	 * 统计厂商是/否个数
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getStatisticsList", method = RequestMethod.POST)
	@ResponseBody
	public String getStatisticsList(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request);
			int pageSize = Integer.parseInt(CommonUtils.valueOf(request.getParameter("pageSize")));
			String currentPage = CommonUtils.valueOf(request.getParameter("currentPage"));
			if(StringUtils.isBlank(currentPage)) {
				currentPage = "1";
			}
			Page page = Page.newBuilder(Integer.parseInt(currentPage),pageSize,null);  
			param.put("page",page);
			
			Map<String,Object> rs = service.getPageDataSt(param);
			page.setTotalRecord(Integer.parseInt(CommonUtils.valueOf(rs.get("totalCount"))));
			List<Map<String,Object>> list = (List<Map<String, Object>>) rs.get("pageData");
			
			json.put("flag", true);
			json.put("datas",list);
			json.put("totalPages",page.getTotalPage());
			json.put("totalData", page.getTotalRecord());
			json.put("currentPage", currentPage);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
}
